<template
  ><!---->
  <div id="awdDetail" class="sceneDetail" v-if="environInfo && drillDetail.id">
    <!-- <div style="color: rgb(27, 76, 184);margin-bottom: 15px">
      <div class="addressIcon"></div>
      <span>当前位置：</span>
      <span style="cursor: pointer" @click="returnPage">{{ title }}</span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333">{{ drillDetail.name }}</span>
    </div> -->
    <div style="margin-bottom: 20px;" class="sceneStep">
      <div class="step-group">
        <Steps :current="currentIndex" direction="vertical" style="width: 100%;">
          <Step
            title="赛前设置"
            @click.native="toPreCompeManage"
            content="提供赛前竞赛团队、题目、成员的管理以及必要任务的管理."
            :class="{ curStep: drillStatus == 1 }"
            :icon="drillStatus == 1 ? 'ios-refresh-circle' : ''"
          ></Step>
          <Step
            :title="'赛中管理' + (drillDetail.progress == 5 ? '(已暂停)' : '')"
            @click.native="toCompeingManage"
            content="提供竞赛过程中的控制，比如暂停比赛、结束竞赛、修改题目信息、对题目显示隐藏的控制、团队禁赛、恢复竞赛、切换竞赛环境、比赛过程中答题得失分的监控、参赛选手操作的监控、题目的环境和题目的状态监控等。"
            :class="{ curStep: drillStatus == 2 }"
            :icon="drillStatus == 2 ? 'ios-refresh-circle' : ''"
          ></Step>
          <Step
            title="赛后归档"
            @click.native="toCompeedManage"
            content="提供赛后选手成绩的管理和统计."
            :class="{ curStep: drillStatus == 3 }"
            :icon="drillStatus == 3 ? 'ios-refresh-circle' : ''"
          ></Step>
        </Steps>
        <p
          style="color:#f00;"
          v-if="projectInfo.status == 3 && drillDetail.progress == 4 && endClearConfig"
        >
          【您的环境将于<Time
            :time="destoryTime"
            type="datetime"
          />时自动回收，若仍需保留，请在回收前重新开始配置比赛】
        </p>
      </div>
      <div class="countdown" v-if="drillDetail.progress != 4">
        <template v-if="drillDetail.progress != 5">
          <span v-if="drillStatus == 1">开始</span
          ><span v-if="drillStatus != 1">结束</span>倒计时：<b>
            <span>{{ time.h }}</span
            >:<span>{{ time.m }}</span
            >:<span>{{ time.s }}</span></b
          >
        </template>
        <strong v-else>
          暂停中
        </strong>
      </div>
      <div class="btn-group">
        <div class="flex">
          <Poptip
            confirm
            title="确定要释放本次比赛的资源吗？如果确定本次比赛的结果已经统计完毕,请继续."
            @on-ok="clearProject()"
            transfer
            word-wrap
            width="250"
          >
            <Button
              type="primary"
              :ghost="destoryProject() || disabledAllBtn"
              :disabled="destoryProject() || disabledAllBtn"
            >
              <img
                src="../../assets/scene/dis-not-deploy.png"
                alt=""
                v-if="destoryProject() || disabledAllBtn"
              />
              <img src="../../assets/scene/not-deploy.png" alt="" v-else />
              <span v-if="projectInfo.status == 14 || projectInfo.status == 3">释放资源</span>
              <span v-else>{{ projectInfo.statusCHName }}</span>
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="为确保可视化展示效果，建议使用chrome浏览器查看大屏。"
            @on-ok="showVisualization('common')"
            transfer
            word-wrap
            width="250"
          >
            <Button type="primary">
              <img src="../../assets/scene/dis-screen.png" />可视化展示
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="为确保可视化展示效果，建议使用chrome浏览器查看大屏。"
            @on-ok="showVisualizationRank('Ranking')"
            transfer
            word-wrap
            width="250"
          >
            <Button type="primary">
              <img src="../../assets/scene/dis-screen.png" />可视化团队排行
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="为确保可视化展示效果，建议使用chrome浏览器查看大屏。"
            @on-ok="showVisualizationQuestion('Question')"
            transfer
            word-wrap
            width="250"
          >
            <Button type="primary">
              <img src="../../assets/scene/dis-screen.png" />可视化题目统计
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="确定要开始比赛？"
            @on-ok="getTaskList('2')"
            transfer
            v-if="drillDetail.progress != 4"
            word-wrap
          >
            <Button type="primary" :ghost="disabledStartCompete" :disabled="disabledStartCompete">
              <img
                src="../../assets/scene/dis-start-scene.png"
                alt=""
                v-if="disabledStartCompete"
              />
              <img src="../../assets/scene/start-scene.png" alt="" v-else />开始比赛
            </Button>
          </Poptip>
          <Button
            type="primary"
            @click="
              showModal(
                '重新开始比赛',
                scoringType === 1 ? ['Dates', 'attackTimeframe', 'defendTimeframe'] : ['Dates'],
                saveScene,
                120
              )
            "
            v-if="drillDetail.progress == 4"
            :ghost="disabledAllBtn"
            :disabled="disabledAllBtn"
          >
            <img src="../../assets/scene/dis-start-scene.png" alt="" v-if="disabledAllBtn" />
            <img src="../../assets/scene/start-scene.png" alt="" v-else />重新开始比赛
          </Button>
          <Button
            type="primary"
            @click="showDelayModal()"
            v-if="drillStatus == 2"
            :ghost="disabledAllBtn"
            :disabled="disabledAllBtn"
          >
            <img src="../../assets/scene/dis-delay.png" alt="" v-if="disabledAllBtn" />
            <img src="../../assets/scene/delay.png" alt="" v-else />延迟比赛
          </Button>
          <Poptip
            confirm
            title="确定要重置环境？"
            @on-ok="resetEnviron()"
            transfer
            v-if="drillDetail.progress == 4 && cloudType !== 'h3c'"
            word-wrap
          >
            <Button
              type="primary"
              :ghost="disabledAllBtn || resetStatus == 1"
              :disabled="disabledAllBtn || resetStatus == 1"
            >
              <template v-if="resetStatus == 1">
                <Progress
                  :percent="resetProgress"
                  :stroke-width="10"
                  style="width:90px"
                  v-if="resetStatus == 1 && drillDetail.progress == 4"
                >
                  <span>重置{{ resetProgress }}%</span>
                </Progress>
              </template>
              <template v-else>
                <img
                  src="../../assets/scene/dis-reset-network.png"
                  alt=""
                  height="16"
                  v-if="disabledAllBtn"
                />
                <img src="../../assets/scene/reset-network.png" alt="" height="16" v-else />重置环境
              </template>
              <Icon
                type="ios-information-circle-outline"
                :size="16"
                @click.stop="getResetDetail"
                v-if="resetFail"
                style="vertical-align:text-bottom;"
              />
            </Button>
          </Poptip>
          <Poptip confirm title="确定要结束比赛？" @on-ok="getTaskList('4')" transfer word-wrap>
            <Button
              type="primary"
              :ghost="stopContestStatus || disabledAllBtn"
              :disabled="stopContestStatus || disabledAllBtn"
            >
              <img
                src="../../assets/scene/dis-stop-scene.png"
                alt=""
                v-if="stopContestStatus || disabledAllBtn"
              />
              <img src="../../assets/scene/stop-scene.png" alt="" v-else />结束比赛
            </Button>
          </Poptip>
          
          <!-- <Poptip
            confirm
            title="确定要暂停比赛？"
            @on-ok="pauseCompetition"
            transfer
            v-if="drillDetail.progress != 5"
            word-wrap
          >
            <Button
              type="primary"
              :ghost="drillDetail.progress != 2 || disabledAllBtn"
              :disabled="drillDetail.progress != 2 || disabledAllBtn"
            >
              <img
                src="../../assets/scene/dis-pause-scene.png"
                alt=""
                v-if="drillDetail.progress != 2 || disabledAllBtn"
              />
              <img src="../../assets/scene/pause-scene.png" alt="" v-else />暂停比赛
            </Button>
          </Poptip>
          <Poptip
            confirm
            title="确定要恢复比赛？"
            @on-ok="restoreCompetition"
            transfer
            v-if="drillDetail.progress == 5"
            word-wrap
          >
            <Button
              type="primary"
              :ghost="drillDetail.progress != 5 || disabledAllBtn"
              :disabled="drillDetail.progress != 5 || disabledAllBtn"
            >
              <img
                src="../../assets/scene/dis-recover-scene.png"
                alt=""
                v-if="drillDetail.progress != 5 || disabledAllBtn"
              />
              <img src="../../assets/scene/recover-scene.png" alt="" v-else />恢复比赛
            </Button>
          </Poptip> -->
          <Button type="primary" @click="boardModal = true">
            <img src="../../assets/scene/dis-boardcast.png" alt="" />发送公告
          </Button>
          <Button type="primary" @click="gotoReportPage" v-if="drillDetail.progress == 4">
            <img src="../../assets/scene/btn-report.png" />报告
          </Button>
          <Poptip
            confirm
            title="确定要清空场景公告及聊天消息？"
            @on-ok="clearSceneNoticeAndChat()"
            transfer
            word-wrap
          >
            <Button type="primary">清空场景公告及聊天信息</Button>
          </Poptip>
          <Button
            type="primary"
            @click="handleGoCircumstances"
            v-if="$store.state.common.sysConfig.modeConfig != '1'"
            >进入环境</Button
          >
        </div>
        <div style="margin-top:5px;">
          <span style="color:#ff9900;font-size:14px"
            ><Icon
              type="ios-information-circle-outline"
              :size="16"
            />开始比赛前请先完成团队人员配置和题目分配,如果已经完成配置,开始按钮不可点,请点击</span
          ><a @click="validateStart" style="font-size: 14px;">校验</a>
        </div>
        <div style="margin-top:5px;">
          <span style="color:#ff9900;font-size:14px"
            ><Icon
              type="ios-information-circle-outline"
              :size="16"
            />如果比赛环境已经被改变，“重新开始比赛”前请先“重置环境”</span
          >
        </div>
        <div style="margin-top:5px;">
          <span style="color:#ff9900;font-size:14px;"
            ><Icon
              type="ios-information-circle-outline"
              :size="16"
            />比赛最长时间间隔为一周,当前时间与比赛结束时间间隔大于一周时不允许开始比赛</span
          >
        </div>
        <ChatRoom v-if="!notOwn" :drillId="drillid" class="btn-chat" ref="chatRoom"></ChatRoom>
      </div>
    </div>
    <div class="span-group">
      <span style="margin-right: 10px;">
        配置模式：<Tag color="blue">{{ configMode === 1 ? '简单模式' : '复杂模式' }}</Tag>
        <Poptip
          confirm
          :title="configModeTitle"
          :disabled="disabledAllBtn"
          @on-ok="changeConfigMode"
        >
          <Button
            type="primary"
            shape="circle"
            icon="md-repeat"
            style="padding: 0;"
            :disabled="disabledAllBtn"
            size="small"
          ></Button>
        </Poptip>
      </span>
      <template v-if="scoringType === 0">
        <span style="margin-right: 10px;" v-if="scoringType === 0">
          无责重置次数：<Tag color="blue">{{ extension.enResetNum }}</Tag>
        </span>
        <span style="margin-right: 10px;" v-if="scoringType === 0">
          超额重置扣分：<Tag color="blue">{{ extension.resetLostScore }}</Tag>
        </span>
      </template>
      <template v-else>
        <span style="margin-right: 10px">
          每题允许提交防御次数：<Tag color="blue">{{ extension.questionAllowDefendCount }}</Tag>
          <Button
            type="primary"
            shape="circle"
            icon="md-repeat"
            @click="
              showModal(
                '修改每题允许提交防御次数',
                ['questionAllowDefendCount'],
                modifyExtension,
                160
              )
            "
            style="padding: 0"
            size="small"
          ></Button>
        </span>
        <span style="margin-right: 10px">
          每题每次提交防御报告间隔 ：<Tag color="blue">{{ extension.submitTime }}（分钟）</Tag>
          <Button
            type="primary"
            shape="circle"
            icon="md-repeat"
            @click="showModal('修改每题每次提交防御报告间隔', ['submitTime'], modifyExtension, 180)"
            style="padding: 0"
            size="small"
          ></Button>
        </span>
        <!-- 没有结束 -->
        <span style="margin-right: 10px">
          当前时段：<Tooltip max-width="320">
            <Tag color="blue">{{ currentTimeframe }}</Tag>
            <template #content>
              <p>攻击时段：</p>
              <br />
              <p
                v-for="(time, index) in showAttackTimeframe"
                :key="`attack${index}`"
                :style="{ color: isCurrentTime(time).color }"
              >
                {{ showTimeNotSecond(time.startTime) }} - {{ showTimeNotSecond(time.endTime) }}（{{
                  isCurrentTime(time).txt
                }}）<br />
              </p>
              <p>防守时段：</p>
              <br />
              <p
                v-for="(time, index) in showDefendTimeframe"
                :key="`defend${index}`"
                :style="{ color: isCurrentTime(time).color }"
              >
                {{ showTimeNotSecond(time.startTime) }} - {{ showTimeNotSecond(time.endTime) }}（{{
                  isCurrentTime(time).txt
                }}）<br />
              </p>
            </template>
          </Tooltip>
          <Button
            type="primary"
            shape="circle"
            icon="md-repeat"
            @click="
              showModal(
                '修改攻击防守时段',
                ['attackTimeframe', 'defendTimeframe'],
                modifyExtension,
                100
              )
            "
            style="padding: 0"
            size="small"
            :disabled="drillStatus === 3"
          ></Button>
        </span>
        <span style="margin-right: 10px">
          曲线降低速率：<Tag color="blue">{{ extension.curveDecelerateRate || 5 }}</Tag>
          <Button
            type="primary"
            shape="circle"
            icon="md-repeat"
            @click="showModal('修改曲线降低速率', ['curveDecelerateRate'], modifyExtension, 100)"
            style="padding: 0"
            size="small"
          ></Button>
        </span>
      </template>
      <span style="margin-right: 10px">
        比赛结束后24小时是否自动销毁环境：<Tag color="blue">{{ endClearConfigShow }}</Tag>
        <Poptip
          confirm
          :title="changeEndClearConfigTip"
          :disabled="disChangeEndClearConfig"
          @on-ok="changEndClearConfig()"
        >
          <Button
            type="primary"
            shape="circle"
            icon="md-repeat"
            style="padding: 0"
            :disabled="disChangeEndClearConfig"
            size="small"
          ></Button>
        </Poptip>
      </span>
      <span style="margin-right: 10px;">
        备用环境套数：<Tag color="blue">{{ environInfo.spareEnvNum }}</Tag>
      </span>
      <span style="margin-right: 10px;">
        允许虚拟接入：<Tag color="blue">{{ environInfo.vmInEnable ? '是' : '否' }} </Tag>
      </span>
      <span style="margin-right: 10px;">
        允许实物接入：<Tag color="blue">{{ environInfo.pmInEnable ? '是' : '否' }}</Tag>
      </span>
      <span style="margin-right: 10px;">
        部署模式：<Tag color="blue">{{ deployMode === 2 ? '路由模式' : '数据通道模式' }}</Tag>
      </span>
    </div>
    <Tabs
      class="demo-tabs-style2"
      @on-click="changePreTab"
      v-show="preCompeManagePanelShow"
      :value="preDefault"
    >
      <TabPane label="竞赛团队管理" name="accessGroup" :index="1">
        <AccessUserToGroup
          v-if="preDefault == 'accessGroup'"
          :type="type"
          :disabledAllBtn="disabledAllBtn"
          :configMode="configMode"
          @setHasUser="setHasUser"
          step="pre"
        ></AccessUserToGroup>
      </TabPane>
      <TabPane label="竞赛题目配置" name="targetTeam" :index="2">
        <TargetTeam
          :configMode="configMode"
          v-if="preDefault == 'targetTeam'"
          :type="type"
          :progress="drillDetail.progress"
          :disabledAllBtn="disabledAllBtn"
        ></TargetTeam>
      </TabPane>
      <TabPane label="接入机器分配" name="accessVm" :index="3" v-if="hasAccessMachine">
        <AccessVmToUser
          :configMode="configMode"
          v-if="preDefault == 'accessVm'"
          :type="type"
          :disabledAllBtn="disabledAllBtn"
        ></AccessVmToUser>
      </TabPane>
      <TabPane label="题目分配" name="targetAllot" :index="4">
        <TargetAllot
          :configMode="configMode"
          v-if="preDefault == 'targetAllot'"
          :type="type"
          :disabledAllBtn="disabledAllBtn"
          @setHasTarget="setHasTarget"
          step="pre"
        ></TargetAllot>
      </TabPane>
      <TabPane label="路由规则下发记录" name="routerRules" :index="5">
        <RouterRules
          v-if="preDefault == 'routerRules'"
          :type="type"
          :disabledAllBtn="disabledAllBtn"
          :deployMode="deployMode"
        ></RouterRules>
      </TabPane>
      <TabPane label="静态Flag配置" name="flagOut" :index="6">
        <FlagOut
          v-if="preDefault == 'flagOut'"
          :configMode="configMode"
          :type="type"
          :disabledAllBtn="disabledAllBtn"
        ></FlagOut>
      </TabPane>
      <!-- <TabPane label="流量过滤" name="flow" :index="8"> //放出来记得改index
                <Flow v-if="preDefault == 'flow'" :disabledAllBtn="disabledAllBtn"></Flow>
            </TabPane> -->
      <!-- <TabPane label="Checker任务" name="checker" :index="10">
        <Checker
          :configMode="configMode"
          v-if="preDefault == 'checker'"
          :type="type"
          :disabledAllBtn="disabledAllBtn"
        ></Checker>
      </TabPane> -->
      <TabPane
        label="答题系统通道配置任务"
        name="protocol"
        v-if="hsaProblemsystem || questionSystemShowTab"
        :index="7"
      >
        <Protocol
          :configMode="configMode"
          v-if="preDefault == 'protocol'"
          :disabledAllBtn="disabledAllBtn"
        ></Protocol>
      </TabPane>
      <!-- <TabPane label="答题环境路由配置" name="distributeRouter" :index="12">
                <DistributeRouter v-if="preDefault == 'distributeRouter'" :disabledAllBtn="disabledAllBtn"></DistributeRouter>
            </TabPane> -->
      <TabPane
        label="选手自带答题设备接入申请"
        name="physicalResource"
        v-if="hasOwnDevice"
        :index="8"
      >
        <physicalResource
          :configMode="configMode"
          v-if="preDefault == 'physicalResource'"
          :disabledAllBtn="disabledAllBtn"
        ></physicalResource>
      </TabPane>
      <!--<TabPane label="数据通道">
                <TargetTeam></TargetTeam>
            </TabPane>-->
    </Tabs>
    <Tabs
      class="demo-tabs-style2"
      @on-click="changeMidTab"
      v-if="compeingManagePanelShow"
      :value="midDefault"
    >
      <TabPane label="竞赛题目配置" name="targetTeam" :index="1">
        <TargetTeam
          :configMode="configMode"
          v-if="midDefault == 'targetTeam'"
          :type="type"
          :progress="drillDetail.progress"
          :disabledAllBtn="disabledAllBtn"
        ></TargetTeam>
      </TabPane>
      <TabPane label="竞赛题目统计" name="targetTeamMid" :index="2">
        <TargetTeamMid
          v-if="midDefault == 'targetTeamMid'"
          :type="type"
          :poll="true"
          :scoringType="scoringType"
        ></TargetTeamMid>
      </TabPane>
      <TabPane label="选手接入机器录屏" name="tab6" :index="3" v-if="hasAccessMachine">
        <screenController v-if="midDefault == 'tab6'"></screenController>
      </TabPane>
      <TabPane label="团队排行统计" name="teamRankStatic" :index="4">
        <teamRankStatic
          v-if="midDefault == 'teamRankStatic'"
          :poll="true"
          :type="type"
          :basisScore="basisScore"
        ></teamRankStatic>
      </TabPane>
      <TabPane label="提交统计" name="submitRecord" :index="5">
        <submitRecord v-if="midDefault == 'submitRecord'" :poll="true" :type="type"></submitRecord>
      </TabPane>
      <!--1.攻击得分、2.防守失分、3.异常失分、4.异常得分、5.防守得分-->
      <TabPane label="攻击得分统计" name="attackSuccess" :index="6">
        <scoreRecordStatic
          v-if="midDefault == 'attackSuccess'"
          :type="1"
          :sceneType="type"
          :poll="true"
          :scoringType="scoringType"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="防守得分统计" name="defenceScore" :index="7">
        <scoreRecordStatic
          v-if="midDefault == 'defenceScore'"
          :type="5"
          :sceneType="type"
          :poll="true"
          :scoringType="scoringType"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="防守失分统计" name="defenceLost" :index="8" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="midDefault == 'defenceLost'"
          :type="2"
          :sceneType="type"
          :poll="true"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="重置失分统计" name="resetLost" :index="9" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="midDefault == 'resetLost'"
          :type="7"
          :sceneType="type"
          :poll="true"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="异常得分统计" name="exceptionLost" :index="10" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="midDefault == 'exceptionLost'"
          :type="4"
          :sceneType="type"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="异常失分统计" name="abnormalScore3" :index="11" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="midDefault == 'abnormalScore3'"
          :type="3"
          :sceneType="type"
          :poll="true"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="防御补丁统计" name="defensePatch" :index="12">
        <defense-patch
          v-if="midDefault == 'defensePatch'"
          :scoringType="scoringType"
        ></defense-patch>
      </TabPane>
      <TabPane label="题目异常日志" name="targetExceptionLog" :index="13">
        <TargetExceptionLog
          v-if="midDefault == 'targetExceptionLog'"
          :type="type"
        ></TargetExceptionLog>
      </TabPane>
      <TabPane label="团队重置记录" name="resetStatic" :index="14">
        <reset-target-static v-if="midDefault == 'resetStatic'"></reset-target-static>
      </TabPane>
      <TabPane label="环境管理" name="environManage" :index="15">
        <EnvironManage v-if="midDefault == 'environManage'"></EnvironManage>
      </TabPane>
      <TabPane label="题目攻防统计" name="problemStatistics" :index="16">
        <problemStatistics v-if="midDefault == 'problemStatistics'"></problemStatistics>
      </TabPane>
    </Tabs>
    <Tabs
      class="demo-tabs-style2"
      @on-click="changeEndTab"
      v-if="compeedManagePanelShow"
      :value="endDefault"
    >
      <TabPane label="团队排行统计" name="teamRankStatic" :index="1">
        <teamRankStatic
          v-if="endDefault == 'teamRankStatic'"
          :type="type"
          :basisScore="basisScore"
          :drillStatus="drillStatus"
        ></teamRankStatic>
      </TabPane>
      <TabPane label="提交统计" name="submitRecord" :index="2">
        <submitRecord v-if="endDefault == 'submitRecord'" :type="type"></submitRecord>
      </TabPane>
      <TabPane label="攻击得分统计" name="attackSuccess" :index="3">
        <scoreRecordStatic
          v-if="endDefault == 'attackSuccess'"
          :type="1"
          :sceneType="type"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="防守得分统计" name="defenceScore" :index="4">
        <scoreRecordStatic
          v-if="endDefault == 'defenceScore'"
          :type="5"
          :sceneType="type"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="防守失分统计" name="defenceLost" :index="5" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="endDefault == 'defenceLost'"
          :type="2"
          :sceneType="type"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="重置失分统计" name="resetLost" :index="6" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="endDefault == 'resetLost'"
          :type="7"
          :sceneType="type"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="异常得分统计" name="exceptionLost" :index="7" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="endDefault == 'exceptionLost'"
          :type="4"
          :sceneType="type"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="异常失分统计" name="abnormalScore3" :index="8" v-if="scoringType === 0">
        <scoreRecordStatic
          v-if="endDefault == 'abnormalScore3'"
          :type="3"
          :sceneType="type"
        ></scoreRecordStatic>
      </TabPane>
      <TabPane label="报告统计" name="reportStatic" :index="9">
        <ReportList v-if="endDefault == 'reportStatic'" :wpUpMode="1" :type="type"></ReportList>
      </TabPane>
      <TabPane label="防御补丁统计" name="defensePatch" :index="10">
        <defense-patch v-if="endDefault == 'defensePatch'"></defense-patch>
      </TabPane>
      <TabPane label="团队积分" name="adwTeamIntegral" :index="11">
        <adwDrillIntegral
          v-if="endDefault == 'adwTeamIntegral'"
          :type="0"
          :sceneType="type"
        ></adwDrillIntegral>
      </TabPane>
      <TabPane label="个人积分" name="adwUserIntegral" :index="12">
        <adwDrillIntegral
          v-if="endDefault == 'adwUserIntegral'"
          :type="1"
          :sceneType="type"
        ></adwDrillIntegral>
      </TabPane>
      <TabPane label="题目攻防统计" name="problemStatistics" :index="13">
        <problemStatistics v-if="endDefault == 'problemStatistics'"></problemStatistics>
      </TabPane>
      <TabPane label="录屏回放" name="tab6" :index="14" v-if="hasAccessMachine">
        <screenController v-if="endDefault == 'tab6'" :poll="false"></screenController>
      </TabPane>
    </Tabs>
    <Modal v-model="boardModal" title="发送公告" :width="650" footer-hide>
      <board v-if="boardModal" @hideModal="hideModal"></board>
    </Modal>
    <Modal
      v-model="sceneModal.show"
      :title="sceneModal.title"
      :loading="sceneModal.loading"
      :mask-closable="false"
      @on-ok="handleSceneModalOk"
      @on-cancel="handleReset('formValidate')"
      :width="600"
    >
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="sceneModal.labelWidth"
      >
        <!-- {{formValidate.Dates}} -->
        <FormItem label="时间" prop="Dates" v-if="sceneModal.prop.includes('Dates')">
          <FormDatepicker
            v-model="formValidate.Dates"
            :disabled="drillStatus !== 3"
            @on-change="handleChangeDates"
          >
          </FormDatepicker>
          <!-- <DatePicker
            :editable="false"
            type="datetimerange"
            :value="formValidate.Dates"
            format="yyyy-MM-dd HH:mm"
            placement="bottom-start"
            confirm
            ref="datePicker"
            placeholder="选择日期"
            style="width: 280px"
            transfer
            @on-ok="clickOkBtn"
            @on-clear="clickClearBtn"
            @on-open-change="switchOpenChange"
            @on-change="handleChangeDates"
            :disabled="drillStatus !== 3"
          ></DatePicker> -->
          <p style="color:#ff9900;font-size:10px">
            选择同一天的时间段，请先双击要选择的日期，最长时间间隔为一周
          </p>
        </FormItem>
        <FormItem
          label="每题允许提交防御次数"
          prop="questionAllowDefendCount"
          v-if="sceneModal.prop.includes('questionAllowDefendCount')"
        >
          <InputNumber v-model="formValidate.questionAllowDefendCount" style="width:100%" />
        </FormItem>
        <FormItem
          label="每题每次提交防御报告间隔"
          prop="submitTime"
          v-if="sceneModal.prop.includes('submitTime')"
        >
          <InputNumber v-model="formValidate.submitTime" style="width:calc(100% - 40px)" /> (分钟)
        </FormItem>
        <template v-if="sceneModal.prop.includes('attackTimeframe')">
          <FormItem label="比赛时间" prop="Dates1" v-if="!sceneModal.prop.includes('Dates')">
            {{ showTimeNotSecond(formValidate.Dates[0]) }} -
            {{ showTimeNotSecond(formValidate.Dates[1]) }}</FormItem
          >
          <FormItem
            v-for="(item, index) in formValidate.attackTimeframe"
            :key="`attack-${index}`"
            :label="index === 0 ? '攻击时段' : ''"
            :prop="'attackTimeframe.' + index + '.time'"
            :rules="[
              {
                required: true,
                type: 'array',
                min: 2,
                max: 2,
                message: '请选择时间',
                trigger: 'change'
              },
              {
                validator: (rule, value, callback) =>
                  validateTime(rule, value, callback, { ...item, index, type: 'attack' })
              }
            ]"
          >
            <div class="flex">
              <FormDatepicker
                v-model="item.time"
                :min="formValidate.Dates[0]"
                :max="formValidate.Dates[1]"
                :disabled="
                  drillStatus === 2 && item.time[0] && serveTime > new Date(item.time[0]).getTime()
                "
                @on-change="(time) => changeTimeframe(time, item, 'attack')"
              >
              </FormDatepicker>
              <!-- <DatePicker
                      :editable="false"
                      type="datetimerange"
                      :value="item.time"
                      format="yyyy-MM-dd HH:mm"
                      placement="bottom-start"
                      ref="datePicker"
                      placeholder="选择日期"
                      style="width: 280px"
                      transfer
                      :options="disableTimeframedOptions"
                      @on-change="(time) => changeTimeframe(time,item,'attack')"
                      transfer-class-name="noConfirm"
                      :disabled="drillStatus === 2 && item.time[0] && serveTime > new Date(item.time[0]).getTime()"
                  ></DatePicker> -->
              <Button
                v-if="index === 0"
                icon="md-add"
                class="ml10"
                style="padding:0"
                @click.prevent="addTimeFrame('attack')"
              ></Button>
              <Button
                v-else
                icon="md-remove"
                class="ml10"
                style="padding:0"
                @click.prevent="removeTimeFrame('attack', index)"
                :disabled="
                  drillStatus === 2 && item.time[0] && serveTime > new Date(item.time[0]).getTime()
                "
              ></Button>
            </div>
            <template v-if="index === formValidate.attackTimeframe - 1">
              <p style="color: #ff9900; font-size: 10px; line-height: 2">
                <Icon type="ios-information-circle-outline" />
                选择同一天的时间段，请先双击要选择的日期
              </p>
              <p style="color: #ff9900; font-size: 10px; line-height: 2">
                <Icon type="ios-information-circle-outline" />
                开始时间不能小于比赛开始时间
              </p>
              <p style="color: #ff9900; font-size: 10px; line-height: 2">
                <Icon type="ios-information-circle-outline" />
                各时段时间不能冲突
              </p>
            </template>
          </FormItem>
        </template>
        <template v-if="sceneModal.prop.includes('defendTimeframe')">
          <FormItem
            v-for="(item, index) in formValidate.defendTimeframe"
            :key="`defend-${index}`"
            :label="index === 0 ? '防守时段' : ''"
            :prop="'defendTimeframe.' + index + '.time'"
            :rules="[
              {
                required: true,
                type: 'array',
                min: 2,
                max: 2,
                message: '请选择时间',
                trigger: 'change'
              },
              {
                validator: (rule, value, callback) =>
                  validateTime(rule, value, callback, { ...item, index, type: 'defend' })
              }
            ]"
          >
            <div class="flex">
              <FormDatepicker
                v-model="item.time"
                :min="formValidate.Dates[0]"
                :max="formValidate.Dates[1]"
                :disabled="
                  drillStatus === 2 && item.time[0] && serveTime > new Date(item.time[0]).getTime()
                "
                @on-change="(time) => changeTimeframe(time, item, 'defend')"
              >
              </FormDatepicker>
              <!-- <DatePicker
                      :editable="false"
                      type="datetimerange"
                      :value="item.time"
                      format="yyyy-MM-dd HH:mm"
                      placement="bottom-start"
                      ref="datePicker"
                      placeholder="选择日期"
                      style="width: 280px"
                      transfer
                      :options="disableTimeframedOptions"
                      @on-change="(time) => changeTimeframe(time,item,'defend')"
                      transfer-class-name="noConfirm"
                      :disabled="drillStatus === 2 && item.time[0] && serveTime > new Date(item.time[0]).getTime()"
                  ></DatePicker> -->
              <Button
                v-if="index === 0"
                icon="md-add"
                class="ml10"
                style="padding:0"
                @click.prevent="addTimeFrame('defend')"
              ></Button>
              <Button
                v-else
                icon="md-remove"
                class="ml10"
                style="padding:0"
                @click.prevent="removeTimeFrame('defend', index)"
                :disabled="
                  drillStatus === 2 && item.time[0] && serveTime > new Date(item.time[0]).getTime()
                "
              ></Button>
            </div>
            <template v-if="index === formValidate.defendTimeframe - 1">
              <p style="color: #ff9900; font-size: 10px; line-height: 2">
                <Icon type="ios-information-circle-outline" />
                选择同一天的时间段，请先双击要选择的日期
              </p>
              <p style="color: #ff9900; font-size: 10px; line-height: 2">
                <Icon type="ios-information-circle-outline" />
                开始时间不能小于比赛开始时间
              </p>
              <p style="color: #ff9900; font-size: 10px; line-height: 2">
                <Icon type="ios-information-circle-outline" />
                各时段时间不能冲突
              </p>
            </template>
          </FormItem>
        </template>
        <FormItem
          label="曲线降低速率"
          prop="curveDecelerateRate"
          v-if="sceneModal.prop.includes('curveDecelerateRate')"
        >
          <InputNumber
            :min="1"
            v-model="formValidate.curveDecelerateRate"
            placeholder="请输入整数"
            style="width: 200px"
          ></InputNumber>
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="sceneDelayModal.show"
      :title="sceneDelayModal.title"
      :loading="sceneDelayModal.loading"
      :mask-closable="false"
      @on-ok="saveSceneDelayTime('formValidate1')"
      @on-cancel="handleReset('formValidate1')"
      :width="600"
    >
      <Form ref="formValidate1" :model="formValidate" :rules="delayRuleValidate" :label-width="80">
        <FormItem label="结束时间" prop="endDate">
          <DatePicker
            :editable="false"
            type="datetime"
            v-model="formValidate.endDate"
            format="yyyy-MM-dd HH:mm"
            placement="bottom-start"
            placeholder="选择日期"
            style="width: 280px"
            transfer
            @on-change="changeEndDate"
          ></DatePicker>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="tipModal.show" :title="tipModal.title" width="300" footer-hide>
      <h4>
        <Icon
          type="ios-loading"
          size="24"
          class="demo-spin-icon-load"
          style="margin-right:24px;"
        ></Icon
        >{{ tipModal.content }}
      </h4>
    </Modal>
    <Modal v-model="resetDetailModal.show" :title="resetDetailModal.title" width="800" footer-hide>
      <Button type="primary" ghost size="small" @click="rebuildAllFailVm" v-if="resetFail">
        <img
          src="../../assets/scene/dis-reset-network.png"
          alt=""
          style="vertical-align: middle;"
        />重置所有重置失败节点
      </Button>
      <Table border :columns="resetCol" :data="resetInfo.msgs" style="margin-top:10px;"></Table>
    </Modal>
    <Modal v-model="ctfDeductionFormValidate.show" title="修改扣分比例">
      <Form
        ref="ctfDeductionFormValidate"
        :model="ctfDeductionFormValidate"
        :label-width="120"
        :rules="ctfDeductionRuleValidate"
      >
        <FormItem label="申请提示扣分比例" prop="ctfDeduction">
          <InputNumber
            style="width: 100%;"
            :max="100"
            :min="1"
            :placeholder="`设置范围：1~100`"
            v-model="ctfDeductionFormValidate.ctfDeduction"
          ></InputNumber>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="
            ctfDeductionFormValidate.show = false
            handleReset('ctfDeductionFormValidate')
          "
          >取消</Button
        >
        <Button @click="changeCtfDeduction" type="primary">确定</Button>
      </div>
    </Modal>
    <automation-step
      @on-window-state-change="windowStateChange"
      @finish="automationStepFinish"
      :disabled="disabledAllBtn"
      :type="type"
    ></automation-step>
  </div>
</template>

<script>
import submitRecord from '@/view/drill_compete/page/statistics/submitRecord.vue'
import TargetTeam from '@/view/drill_compete/page/targetTeam/targetTeam-adc' //靶机
import TargetAllot from '@/view/drill_compete/page/targetTeam/targetTeamAllot-adc' //靶标分配
import RouterRules from '@/view/drill_compete/page/router-rules' // 路由规则最新的下发记录
import AccessVmToUser from '@/view/drill_compete/page/accessVmToUser'
import TargetTeamMid from '@/view/drill_compete/page/targetTeam/targetTeam-mid-new'
// import Checker from '@/view/drill_compete/page/task_new/checker';
import FlagOut from '@/view/drill_compete/page/task_new/flagOut.vue'
import FlagVmOnce from '@/view/drill_compete/page/flagVmOnce'
import problemStatistics from '@/view/drill_compete/page/problemStatistics'
import AccessUserToGroup from '@/view/drill_compete/page/accessUserToGroup'
import TargetExceptionLog from '@/view/drill_compete/page/awdTargetExceptionLog'
import physicalResource from '@/view/drill_compete/page/physicalResource'
import Protocol from '@/view/drill_compete/page/protocol.vue'
import QGAWrite from '@/view/drill_compete/page/qgaWrite/qgawrite.vue'
import adwDrillIntegral from '@/view/drill_compete/page/statistics/awdDrillIntegral.vue' //积分
import teamRankStatic from '@/view/drill_compete/page/statistics/adcTeamRankStatic.vue'
import scoreRecordStatic from '@/view/drill_compete/page/statistics/adcScoreRecordStatic.vue'
import DistributeRouter from '@/view/drill_compete/page/distributeRouter.vue'
import board from '@/components/board-cast/drillBoardcast.vue'
import EnvironManage from '@/view/drill_compete/page/environManage.vue'
import ChatRoom from '@/components/chatRoom/chatRoom'
import encryption from '@/libs/encryption.js'
import AutomationStep from '@/components/automation-step/automation-step'
import ResetTargetStatic from '@/components/reset-target-static/reset-target-static'
import DefensePatch from '@/components/defense-patch/defense-patch'
import FormDatepicker from '@/components/common/form-datepicker'
import {
  getSceneInfo,
  updateSceneProgress,
  setSceneCycle,
  modifyScene,
  quickCreateProgress,
  batchOpVm,
  batchOpVmLog,
  batchOpVmLogOnce,
  rebuildVm,
  addSceneCycle
} from '@/api/drill_compete'
import { clearProject } from '@/api/competition'
import { getTaskList, batchActiveTask, getstatusbyprjid } from '@/api/drill'
import { clearSceneNoticeAndChat, sendToSence } from '@/api/boardcast_new.js'
import timer from '@/mixin/timer'
import commonFun from './mixin.js'
import screenController from '@/view/drill_compete/page/screenController'
import { mapState } from 'vuex'
import recoverTime from '@/mixin/recoverTime'
import { parseJson, showTimeNotSecond } from '@/libs/utils'
import ReportList from '@/view/drill_compete/page/report-list'
import { getaccessgrouplist } from '@/api/access_new.js'
import destroyEnv from '@/mixin/destroyEnvironmentMixin'
import resetSceneMixin from '@/mixin/resetSceneMixin'
import { getNumReg } from '@/libs/reg'
export default {
  name: 'scenes',
  components: {
    DefensePatch,
    ReportList,
    ResetTargetStatic,
    AutomationStep,
    screenController,
    TargetTeam, //靶机--演练前
    submitRecord,
    TargetAllot,
    RouterRules,
    TargetTeamMid, //靶机--演练中（poll="true"）会轮询,
    // Checker, //check任务
    FlagOut, //
    FlagVmOnce, //Flag服务器配置
    AccessVmToUser, //（环境）接入机器
    AccessUserToGroup, //（演练用户管理）分配用户
    TargetExceptionLog, //靶标异常日志
    Protocol, //数据通道任务
    QGAWrite, //路由下发（文件导入）
    adwDrillIntegral, //积分
    teamRankStatic, //团队排行
    scoreRecordStatic, //得失分记录
    physicalResource,
    board,
    DistributeRouter,
    EnvironManage,
    ChatRoom,
    problemStatistics,
    FormDatepicker
  },
  mixins: [timer, commonFun, recoverTime, destroyEnv, resetSceneMixin],
  data() {
    let September = sessionStorage.getItem('November')
    September = JSON.parse(encryption.SelfUseDecrypt(September))
    const validateDate = (rule, value, callback) => {
      //验证只能填入数字
      //验证警戒值
      let startTime = this.formValidate.Dates[0]
      let endTime = this.formValidate.Dates[1]
      if (value) {
        if (!startTime || !endTime) {
          callback(new Error('请选择时间'))
        } else if (
          this.drillDetail.progress != 2 &&
          new Date(startTime).getTime() < new Date().getTime()
        ) {
          callback(new Error('开始时间必须大于当前时间'))
        } else if (
          new Date(value[1]).getTime() - new Date(value[0]).getTime() >
          7 * 24 * 60 * 60 * 1000
        ) {
          callback(new Error('最长时间间隔为一周'))
        } else if (new Date(endTime).getTime() - new Date(startTime).getTime() < 60 * 60 * 1000) {
          callback(new Error('起止时间最小间隔一个小时'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择时间'))
      }
    }
    const validateDelayDate = (rule, value, callback) => {
      //验证只能填入数字
      //var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
      //验证警戒值
      if (value) {
        if (
          new Date(value).getTime() - new Date(this.drillDetail.startTime).getTime() >
          7 * 24 * 60 * 60 * 1000
        ) {
          callback(new Error('最长时间间隔为一周'))
        } else if (new Date(value).getTime() - new Date(this.drillDetail.endTime).getTime() <= 0) {
          callback(new Error('选择的时间必须大于当前结束时间'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择时间'))
      }
    }
    const validateNum1 = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^([1-9]|[1-9]\\d|100)$')
      let _this = this
      //验证警戒值
      if (value || value === 0) {
        if (!reg.test(value)) {
          callback(new Error('请输入1-100的整数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validateTime = (rule, value, callback, cur) => {
      //验证警戒值\
      let _this = this
      let [startTime, endTime] = value || []
      let [sceneStartTime, sceneEndTime] = _this.formValidate.Dates
      if (!startTime || !endTime) {
        callback(new Error('请选择时间'))
      } else if (value.length > 0) {
        let attackTimeframe = [..._this.formValidate.attackTimeframe]
        let defendTimeframe = [..._this.formValidate.defendTimeframe]
        if (cur.type === 'attack') {
          attackTimeframe.splice(cur.index, 1)
        } else if (cur.type === 'defend') {
          defendTimeframe.splice(cur.index, 1)
        }
        let times = [...attackTimeframe, ...defendTimeframe]
        let hasConflict = times.some((time) => {
          return (
            new Date(startTime).getTime() < new Date(time.time[1]).getTime() &&
            new Date(endTime).getTime() > new Date(time.time[0]).getTime()
          )
        })
        if (new Date(startTime).getTime() < new Date(sceneStartTime).getTime()) {
          callback(new Error('开始时间不能小于比赛开始时间'))
        } else if (new Date(endTime).getTime() > new Date(sceneEndTime).getTime()) {
          callback(new Error('结束时间不能大于比赛结束时间'))
        } else if (startTime === endTime) {
          callback(new Error('结束时间不能等于开始时间'))
        } else if (
          new Date(endTime).getTime() - new Date(startTime).getTime() <=
          _this.extension.cycleTime * 60 * 1000
        ) {
          callback(new Error(`各时段时长必须大于周期时长（${_this.extension.cycleTime}分钟）`))
        } else if (hasConflict) {
          callback(new Error('时段时间冲突'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      validateTime,
      showTimeNotSecond,
      accessGroupList: [],
      ctfDeductionRuleValidate: {
        ctfDeduction: [
          { required: true, type: 'number', message: '不能为空', trigger: 'change' },
          { validator: validateNum1, trigger: 'change' }
        ]
      },
      ctfDeductionFormValidate: {
        ctfDeduction: 20,
        show: false
      },
      configModeTitle: '是否切换至简单模式',
      environInfo: {},
      autoConfigIsFinish: false,
      USER_ID: September.userId,
      USER_Name: September.nickname,
      projectId: this.$route.query.prjid,
      type: 8, // 攻防赛Plus
      drillid: this.$route.query.id,
      drillName: this.$route.query.name,
      drillDetail: {},
      testid: this.$route.query.id,
      currentIndex: 0,
      preCompeManagePanelShow: true,
      compeingManagePanelShow: false,
      compeedManagePanelShow: false,
      startContestStatus: false,
      stopContestStatus: false,
      preDefault: '',
      midDefault: '',
      endDefault: '',
      drillStatus: '',
      backObj: {
        path: '/awdPlusContest',
        name: 'awdPlusContest',
        query: {
          page: this.$route.query.page
        },
        meta: {
          requireAuth: true
        }
      },
      project: {
        drillitemname: this.$route.query.name,
        projectid: this.$route.query.prjid,
        drillitemid: this.$route.query.id,
        testId: this.$route.query.id
      },
      testid: this.$route.query.id, //工程场景id
      projectInfo: {},
      timeout: {},
      boardModal: false,
      compReportModal: false,
      sceneModal: {
        show: false,
        title: '修改时间',
        loading: true,
        type: 1,
        width: 550,
        prop: []
      },
      sceneDelayModal: {
        show: false,
        title: '延迟比赛时间',
        loading: true,
        type: 1,
        width: 550
      },
      formValidate: {
        cycleTime: 1,
        description: '',
        endTime: '',
        extension: '',
        iconPath: '',
        id: '',
        name: '',
        progress: 0, // 0.准备中、1.准备完毕、2.开始中、3.裁判评判阶段、4.结束
        projectId: '',
        projectName: '',
        startTime: '',
        status: 1, //0 ：不启用 1：启用
        type: 0, //0.对抗演练、1.攻防赛、2夺旗赛、3知识赛、4渗透演练
        Dates: [],
        stMode: 0,
        endDate: '',
        questionAllowDefendCount: 300,
        submitTime: 1,
        attackTimeframe: [],
        defendTimeframe: [],
        curveDecelerateRate: 5
      },
      ruleValidate: {
        Dates: [
          { required: true, type: 'array', message: '不能为空', trigger: 'change' },
          { validator: validateDate, trigger: 'change,blur' }
        ],
        questionAllowDefendCount: [
          {
            required: true,
            type: 'number',
            trigger: 'change, blur',
            validator: getNumReg(1000)
          }
        ],
        submitTime: [
          {
            required: true,
            type: 'number',
            trigger: 'change, blur',
            validator: getNumReg(100)
          }
        ],
        attackTimeframe: [
          {
            required: true,
            type: 'array',
            min: 1,
            max: 1,
            message: '不能为空',
            trigger: 'change, blur',
            defaultField: [
              {
                validator: validateTime
              }
            ]
          }
        ],
        defendTimeFrame: [
          {
            required: true,
            type: 'array',
            min: 1,
            max: 1,
            message: '不能为空',
            trigger: 'change, blur'
          }
        ],
        curveDecelerateRate: [
          {
            required: true,
            type: 'number',
            trigger: 'change, blur',
            validator: getNumReg()
          }
        ]
      },
      delayRuleValidate: {
        endDate: [{ validator: validateDelayDate, trigger: 'change' }]
      },
      disabledDestroy: false,
      destoryTime: '',
      tipModal: {
        title: '提示',
        show: false,
        content: ''
      },
      queryOpLogInfo: {
        pageIndex: 1,
        pageSize: 10,
        projectId: this.$route.query.prjid,
        action: 'rebuild'
      },
      isAllowApplicationPrompt: 1,
      applicationPromptPlayTitle: '是否关闭提示申请',
      ctfDeduction: 20,
      resetProgress: 0,
      resetInfo: {},
      resetStatus: 0,
      resetFail: false,
      resetDetailModal: {
        title: '重置详情',
        show: false
      },
      resetCol: [
        {
          title: '虚拟机名称',
          key: 'name'
        },
        {
          title: '实例名称',
          key: 'instanceName'
        },
        {
          title: '系统类型',
          key: 'sysType'
        },
        {
          title: '子网络名称',
          key: 'networkName'
        },
        {
          title: '镜像名称',
          key: 'imageName'
        },
        {
          title: '状态',
          key: 'errMsg',
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color: params.row.errMsg ? 'red' : 'green'
                }
              },
              params.row.errMsg ? '重置失败' : '重置成功'
            )
          }
        },
        {
          title: '错误信息',
          key: 'errMsg',
          render: (h, params) => {
            return h('span', params.row.errMsg || '无')
          }
        }
      ],
      isWindowed: false
    }
  },
  filters: {},
  provide() {
    return {
      parent: this,
      detailParent: this
    }
  },
  beforeDestroy() {
    clearTimeout(this.timeout)
    clearInterval(this.timeoutP)
    clearTimeout(this.setTimeInter)
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/awdPlusContest') {
      next()
    } else {
      //跳转至非攻防赛页面，清空存储的查询条件
      sessionStorage.removeItem('queryObj')
      next()
    }
  },
  computed: {
    ...mapState('board', ['notReadCount', 'notReadChatCount']), //未读消息数
    disabledStartCompete() {
      return (
        this.startContestStatus ||
        this.disabledAllBtn ||
        this.disStartCompete ||
        new Date(this.drillDetail.endTime).getTime() - this.serveTime > 7 * 24 * 60 * 60 * 1000
      )
    },
    disabledAllBtn() {
      return (
        this.projectInfo.status != 3 || this.drillDetail.creator != this.USER_ID || this.isWindowed
      )
    },
    extension() {
      return parseJson(this.drillDetail && this.drillDetail.extension)
    },
    deployMode() {
      return this.extension.deployMode || 2
    },
    scoringType() {
      return this.extension.scoringType || 0
    },
    configMode() {
      return this.extension.configMode || 2
    },
    hasAccessMachine() {
      // 有虚拟接入设备
      return this.environInfo.vmInEnable
    },
    hasOwnDevice() {
      // 有自带实物接入设备
      return this.environInfo.pmInEnable
    },
    hsaProblemsystem() {
      // 有答题系统
      return this.deployMode !== 2 && this.hasOwnDevice
    },
    basisScore() {
      return this.extension.basicScore || 5000
    },
    notOwn() {
      return this.drillDetail.creator !== this.USER_ID
    },
    title() {
      //当前菜单显示名
      return this.$store.getters.pageTitle
    },
    disableTimeframedOptions() {
      let [startTime, endTime] = this.formValidate.Dates
      if (!startTime || !endTime) {
        return {}
      }
      return {
        disabledDate(date) {
          return (
            date &&
            (date.valueOf() > new Date(endTime.split(' ')[0] + ' 23:59:59').getTime() ||
              date.valueOf() < new Date(startTime.split(' ')[0] + ' 00:00:00').getTime())
          )
        }
      }
    },
    showAttackTimeframe() {
      return this.extension.attackTimeframe.sort(
        (a, b) => new Date(b.startTime).getTime() - new Date(a.endTime).getTime()
      )
    },
    showDefendTimeframe() {
      return this.extension.defendTimeframe.sort(
        (a, b) => new Date(b.startTime).getTime() - new Date(a.endTime).getTime()
      )
    },
    currentTimeframe() {
      let { attackTimeframe = [], defendTimeframe = [] } = this.extension
      let attackTime = attackTimeframe.find(
        (time) =>
          this.serveTime >= new Date(time.startTime).getTime() &&
          this.currentTime <= new Date(time.endTime).getTime()
      )
      let defendTime = defendTimeframe.find(
        (time) =>
          this.serveTime >= new Date(time.startTime).getTime() &&
          this.currentTime <= new Date(time.endTime).getTime()
      )
      return attackTime && this.drillStatus === 2
        ? `攻击时段（${showTimeNotSecond(attackTime.startTime)} - ${showTimeNotSecond(
            attackTime.endTime
          )}）`
        : defendTime && this.drillStatus === 2
        ? `防守时段（${showTimeNotSecond(defendTime.startTime)} - ${showTimeNotSecond(
            defendTime.endTime
          )}）`
        : '无'
    },
    currentMode() {
      //攻击模式还是防守模式
      let { attackTimeframe = [], defendTimeframe = [] } = this.extension
      if (
        attackTimeframe.some(
          (time) =>
            this.serveTime >= new Date(time.startTime).getTime() &&
            this.currentTime <= new Date(time.endTime).getTime()
        )
      ) {
        return '攻击时段'
      } else if (
        defendTimeframe.some(
          (time) =>
            this.serveTime >= new Date(time.startTime).getTime() &&
            this.currentTime <= new Date(time.endTime).getTime()
        )
      ) {
        return '防守时段'
      } else {
        return '无'
      }
    }
  },
  watch: {
    isAllowApplicationPrompt: function(newValue) {
      if (newValue !== 0) {
        this.applicationPromptPlayTitle = '是否关闭提示申请'
      } else {
        this.applicationPromptPlayTitle = '是否开启提示申请'
      }
    },
    drillStatus(val, oldVal) {
      if (val != oldVal && oldVal) {
        this.getDrillDetail(true, true)
      }
    },
    configMode: function(newValue) {
      if (newValue !== 2) {
        this.configModeTitle = '是否切换至复杂模式'
      } else {
        this.configModeTitle = '是否切换至简单模式'
      }
    }
  },
  async mounted() {
    this.questionSystemShow('questionSystemConfig')
    this.getDrillDetail(true, true).then((data) => {
      this.$store.commit('addBreadItem', { name: this.drillDetail.name })
      //判断是否可以开始比赛
      this.canStartCompete(this.drillDetail.type)
    })
    this.getProjectInfo()
    await quickCreateProgress(this.drillid).then((data) => {
      if (data.code === 1) {
        if (data.data) {
          this.environInfo = JSON.parse(data.data.paramJson)
        }
      }
    })
    sessionStorage.removeItem('vmCurrentPage')
    this.getAccessGroupList()
  },
  methods: {
    // isCurrentTime(time){
    //   return this.serveTime >= new Date(time.startTime).getTime() && this.serveTime <= new Date(time.endTime).getTime()
    // },
    isCurrentTime(time) {
      if (
        this.drillStatus === 2 &&
        this.serveTime >= new Date(time.startTime).getTime() &&
        this.serveTime <= new Date(time.endTime).getTime()
      ) {
        return {
          color: `var(--status-ing)`,
          txt: '进行中'
        }
      } else if (this.serveTime < new Date(time.startTime).getTime()) {
        return {
          color: `var(--status-pre)`,
          txt: '准备中'
        }
      } else {
        return {
          color: `var(--status-end)`,
          txt: '已结束'
        }
      }
    },
    addTimeFrame(type) {
      this.formValidate[`${type}Timeframe`].push({ time: [] })
    },
    removeTimeFrame(type, index) {
      this.formValidate[`${type}Timeframe`].splice(index, 1)
      this.validateConfigTimes('', type)
    },
    changeTimeframe(time, item, type) {
      // let [startTime,endTime] = time;
      // let [sceneStartTime,sceneEndTime] = this.formValidate.Dates;
      // if(new Date(startTime).getTime() < new Date(sceneStartTime).getTime()){
      //     startTime = sceneStartTime
      // }
      // if(new Date(endTime).getTime() > new Date(sceneEndTime).getTime()){
      //     endTime = sceneEndTime
      // }
      // if(startTime && endTime){
      //   item.time = [`${startTime}:00`,`${endTime}:00`]
      // }else{
      //   item.time = []
      // }
      this.validateConfigTimes(item.index, type)
    },
    validateConfigTimes(cindex, type) {
      this.formValidate.attackTimeframe.forEach((time, index) => {
        if ((type === 'attack' && cindex === index) || time.time.length == 0 || !time.time[0]) {
          return
        }
        this.$refs['formValidate'].validateField(`attackTimeframe.${index}.time`, (error) => {
          // resolve(error);
        })
      })
      this.formValidate.defendTimeframe.forEach((time, index) => {
        if ((type === 'defend' && cindex === index) || time.time.length == 0 || !time.time[0]) {
          return
        }
        this.$refs['formValidate'].validateField(`defendTimeframe.${index}.time`, (error) => {
          // resolve(error);
        })
      })
    },
    handleChangeDates(time) {
      // this.formValidate.attackTimeframe = [{time:[]}];
      // this.formValidate.defendTimeframe = [{time:[]}];
      // this.changeDates(...args)
      if (time) {
        this.formValidate.startTime = time[0]
        this.formValidate.endTime = time[1]
      } else {
        this.formValidate.startTime = ''
        this.formValidate.endTime = ''
      }
      this.validateConfigTimes()
    },
    //进入环境
    handleGoCircumstances() {
      if (this.$store.state.common.sysConfig.modeConfig == '2') {
        this.$Message.info('未授权功能，请联系管理员')
      } else if (this.$store.state.common.sysConfig.modeConfig == 'jizhi2024') {
        window.open(
          `/14-topologyProject/index.html#/topologyDisplay/topologys?projectId=${this.$route.query.prjid}`
        )
      }
    },
    // 修改申请提示扣分的比率
    changeCtfDeduction() {
      this.$refs.ctfDeductionFormValidate.validate((valid) => {
        if (valid) {
          let extension = JSON.parse(this.formValidate.extension)
          extension.ctfDeduction = this.ctfDeductionFormValidate.ctfDeduction
          this.formValidate.extension = JSON.stringify(extension)
          let formValidate = {
            extension: this.formValidate.extension
          }
          this.ctfDeduction = this.ctfDeductionFormValidate.ctfDeduction
          this.modifyScene(this.formValidate.id, formValidate, 'changeCtfDeduction')
        }
      })
    },
    // 切换是否允许申请提示
    changeAllowApplicationPrompt() {
      let extension = parseJson(this.drillDetail.extension)
      let isAllowApplicationPrompt = extension.isAllowApplicationPrompt
      isAllowApplicationPrompt = isAllowApplicationPrompt === 0 ? 1 : 0
      // 取反
      extension.isAllowApplicationPrompt = isAllowApplicationPrompt
      this.isAllowApplicationPrompt = isAllowApplicationPrompt
      // this.formValidate.extension = JSON.stringify(extension);
      let formValidate = {
        extension: JSON.stringify(extension)
      }
      this.modifyScene(this.drillDetail.id, formValidate, 'changeAllowApplicationPrompt')
    },
    changeConfigMode() {
      let extension = JSON.parse(this.drillDetail.extension)
      let configMode = extension.configMode
      configMode = configMode !== 2 ? 2 : 1
      extension.configMode = configMode
      this.drillDetail.extension = JSON.stringify(extension)
      // this.formValidate.extension = JSON.stringify(extension);
      let formValidate = {
        extension: JSON.stringify(extension)
      }
      this.modifyScene(this.drillDetail.id, formValidate, 'changeConfigMode')
    },
    changEndClearConfig() {
      let extension = JSON.parse(this.drillDetail.extension)
      extension.endClearConfig = this.endClearConfig ? 0 : 1
      let formValidate = {
        extension: JSON.stringify(extension)
      }
      this.modifyScene(this.drillDetail.id, formValidate, 'changeEndClearConfig').then(() => {
        this.drillDetail.extension = JSON.stringify(extension)
      })
    },
    modifyExtension(data) {
      let extension = JSON.parse(this.formValidate.extension)
      this.sceneModal.prop.forEach((item) => {
        if (['attackTimeframe', 'defendTimeframe'].includes(item)) {
          extension[item] = this.formValidate[item].map((item) => {
            return {
              startTime: item.time[0],
              endTime: item.time[1]
            }
          })
        } else {
          extension[item] = this.formValidate[item]
        }
      })
      let formValidate = { extension: JSON.stringify(extension) }
      this.modifyScene(this.formValidate.id, formValidate, this.sceneModal.prop.join(','))
    },
    // 监控子组件是否处于窗口状态，需要通过这个状态太判断是否需要禁用按钮功能
    windowStateChange(state) {
      this.isWindowed = state
    },
    // 自动配置完成，放开窗口状态监控，检测是否可以开始比赛
    automationStepFinish() {
      this.isWindowed = false
      this.canStartCompete(this.drillDetail.type)
    },
    
    getProjectInfo() {
      if (!this.$route.query.prjid) {
        return
      }
      this.disabledDestroy = false
      getstatusbyprjid(this.$route.query.prjid).then((data) => {
        if (data.code == 1) {
          this.projectInfo = data.attribute.project
          if (
            this.projectInfo.status == 0 ||
            this.projectInfo.status == 10 ||
            this.projectInfo.status == 14
          ) {
            clearInterval(this.timeoutP)
          }
        } else if (data.code == -2) {
          this.projectInfo.statusCHName = '工程不存在'
          this.disabledDestroy = true
        } else {
          this.$Message.error(data.message)
        }
      })
    },
    getDrillDetail(needChangeStep, needServiceTime, setParams) {
      //是否需要切换步骤
      return new Promise((resolve, reject) => {
        getSceneInfo(this.drillid).then((data) => {
          let startTimeChange = false
          let endTimeChange = false
          if (data.data.startTime != this.drillDetail.startTime) {
            startTimeChange = true
          }
          if (data.data.endTime != this.drillDetail.endTime) {
            endTimeChange = true
          }
          this.drillDetail = data.data
          this.destoryTime = new Date(this.drillDetail.endTime).getTime() + 24 * 60 * 60 * 1000
          // this._formValidate = Object.assign(this.formValidate, data.data);
          // if (setParams == 'setEndDate') {
          //   this.formValidate.endDate = data.data.endTime;
          // }
          let isAllowApplicationPrompt = 1
          let ctfDeduction = 20
          if (data.data.extension) {
            let extension = parseJson(data.data.extension)
            if (extension.isAllowApplicationPrompt !== undefined) {
              isAllowApplicationPrompt = extension.isAllowApplicationPrompt
            }
            if (extension.ctfDeduction !== undefined) {
              ctfDeduction = extension.ctfDeduction
            }
          }
          this.isAllowApplicationPrompt = isAllowApplicationPrompt
          this.ctfDeduction = ctfDeduction
          if (this.drillDetail.progress == 0 || this.drillDetail.progress == 1) {
            if (needChangeStep) {
              this.toPreCompeManage()
            }
            if (needServiceTime || startTimeChange) {
              if (this.timeout) {
                clearTimeout(this.timeout)
              }
              this.getServeTime(new Date(this.drillDetail.startTime).getTime())
            }
            this.drillStatus = 1
            this.startContestStatus = false
            this.stopContestStatus = true
          } else if (
            this.drillDetail.progress == 2 ||
            this.drillDetail.progress == 3 ||
            this.drillDetail.progress == 5
          ) {
            if (needChangeStep) {
              this.toCompeingManage()
            }
            if (needServiceTime || endTimeChange) {
              if (this.timeout) {
                clearTimeout(this.timeout)
              }
              this.getServeTime(new Date(this.drillDetail.endTime).getTime())
            }
            this.drillStatus = 2
            this.startContestStatus = true
            this.stopContestStatus = false
          } else if (this.drillDetail.progress == 4) {
            if (needChangeStep) {
              this.toCompeedManage()
            }
            if (needServiceTime || endTimeChange) {
              if (this.timeout) {
                clearTimeout(this.timeout)
              }
              this.getServeTime(new Date(this.drillDetail.endTime).getTime())
            }
            this.drillStatus = 3
            this.startContestStatus = true
            this.stopContestStatus = true
          }
          resolve()
        })
      })
    },
    handleReset(name) {
      this.$refs[name].resetFields()
      this.iconSrc = ''
      this.formValidate.iconPath = ''
    },
    cancelLoading(modal) {
      modal.loading = false
      setTimeout(() => {
        modal.loading = true
      })
    },
    showModal(title, prop, saveFun, labelWidth) {
      this.sceneModal.title = title
      this.sceneModal.prop = prop
      this.sceneModal.labelWidth = labelWidth
      this.sceneModal.ok = saveFun
      this.sceneModal.show = true
      this.sceneModal.type = '2'
      this.getDrillDetail().then((data) => {
        this.formValidate = Object.assign(this.formValidate, this.drillDetail)
        this.$set(this.formValidate, 'Dates', [
          this.drillDetail.startTime,
          this.drillDetail.endTime
        ])
        let extension = parseJson(this.drillDetail.extension)
        if (extension.scoringType === 1) {
          this.formValidate.questionAllowDefendCount = extension.questionAllowDefendCount
          this.formValidate.submitTime = extension.submitTime
          this.formValidate.attackTimeframe = extension.attackTimeframe.map((item) => {
            return {
              time: [item.startTime, item.endTime]
            }
          })
          this.formValidate.defendTimeframe = extension.defendTimeframe.map((item) => {
            return {
              time: [item.startTime, item.endTime]
            }
          })
          this.formValidate.curveDecelerateRate = extension.curveDecelerateRate || 5
        }
      })
    },
    handleSceneModalOk() {
      this.$refs.formValidate
        .validate((valid) => {
          if (valid) {
            this.sceneModal.ok()
          } else {
            this.cancelLoading(this.sceneModal)
          }
        })
        .catch(() => {
          this.cancelLoading(this.sceneModal)
        })
    },
    // modifyDates(){
    //   let data = JSON.parse(JSON.stringify(this.formValidate));
    //   if (new Date(data.startTime).getTime() > new Date(data.endTime).getTime()) {
    //     this.$Message.error('表单输入有误，开始时间不能大于结束时间!');
    //     this.cancelLoading(this.sceneModal);
    //     return;
    //   }
    //   delete data.Dates;
    //   this.modifyScene(data.id, data, 'restart');
    // },
    saveScene() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.formValidate))
          let extension = JSON.parse(data.extension)
          let { attackTimeframe, defendTimeframe } = data
          extension.attackTimeframe = attackTimeframe.map((item) => {
            return {
              startTime: item.time[0],
              endTime: item.time[1]
            }
          })
          extension.defendTimeframe = defendTimeframe.map((item) => {
            return {
              startTime: item.time[0],
              endTime: item.time[1]
            }
          })
          data.extension = JSON.stringify(extension)
          delete data.attackTimeframe
          delete data.defendTimeframe
          this.modifyScene(data.id, data, 'restart')
        } else {
          this.$Message.error('表单输入有误，请查看页面信息后重新输入!')
          this.cancelLoading(this.sceneModal)
        }
      })
    },
    saveSceneDelayTime(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.formValidate))
          delete data.Dates
          data.endTime = data.endDate
          delete data.endDate
          this.modifyScene(data.id, data, 'delay')
        } else {
          this.$Message.error('表单输入有误，请查看页面信息后重新输入!')
          this.cancelLoading(this.sceneDelayModal)
        }
      })
    },
    modifyScene(id, data, type) {
      return new Promise((resolve, reject) => {
        modifyScene(id, data)
          .then((data) => {
            if (data.code == 1) {
              this.sceneModal.show = false
              this.sceneDelayModal.show = false
              this.ctfDeductionFormValidate.show = false
              if (type == 'delay') {
                this.$Message.info('延迟成功')
                this.addSceneCycle()
                setTimeout(() => {
                  this.getDrillDetail(false, true)
                }, 2000)
              } else if (type === 'changeConfigMode') {
                this.$Message.info('模式切换成功')
              } else if (type === 'changeAllowApplicationPrompt') {
                let messageText
                if (this.isAllowApplicationPrompt === 1) {
                  messageText = '允许申请提示'
                } else {
                  messageText = '不允许申请提示'
                }
                this.$Message.info(messageText)
                // 切换是否允许申请，发送公告
                if (this.accessGroupList.length) {
                  // 比赛包含用户，开始为用户发送公告
                  let params = {
                    sceneId: this.$route.query.id,
                    noticeSceneDto: {
                      accessGroups: this.accessGroupList,
                      content: messageText,
                      id: '',
                      title: `5/${this.isAllowApplicationPrompt}`,
                      type: 1 // 切换盲打模式，发送的是实物公告
                    }
                  }
                  sendToSence(params)
                    .then((data) => {
                      if (data.code == 1) {
                      } else {
                        this.$Message.warning(data.message)
                      }
                      this.disabledSend = false
                    })
                    .catch(() => {
                      this.$Message.error('公告发送失败')
                      this.disabledSend = false
                    })
                }
              } else if (type === 'changeCtfDeduction') {
                if (this.accessGroupList.length) {
                  // 比赛包含用户，开始为用户发送公告
                  let params = {
                    sceneId: this.$route.query.id,
                    noticeSceneDto: {
                      accessGroups: this.accessGroupList,
                      content: `申请提示的扣分比例已修改为${this.ctfDeduction}%`,
                      id: '',
                      title: `7/${this.ctfDeduction}`,
                      type: 1 // 修改扣分比例，发送的是实物公告
                    }
                  }
                  this.$Message.info(`申请提示的扣分比例已修改为${this.ctfDeduction}%`)
                  sendToSence(params)
                    .then((data) => {
                      if (data.code == 1) {
                      } else {
                        this.$Message.warning(data.message)
                      }
                      this.disabledSend = false
                    })
                    .catch(() => {
                      this.$Message.error('公告发送失败')
                      this.disabledSend = false
                    })
                }
              } else if (type === 'questionAllowDefendCount') {
                this.$Message.info('修改每题允许提交防御次数成功')
                this.getDrillDetail()
              } else if (type === 'submitTime') {
                this.$Message.info('修改每题每次提交防御报告间隔成功')
                this.getDrillDetail()
              } else if (type === 'attackTimeframe,defendTimeframe') {
                this.$Message.info('修改攻防时间段成功')
                this.getDrillDetail()
              } else if (type === 'changeEndClearConfig') {
                this.$Message.info('切换结束后是否销毁环境成功')
              } else {
                if (type == 'restart') {
                  this.$Message.info('重新开始比赛成功')
                }
                setTimeout(() => {
                  this.getDrillDetail()
                }, 2000)
              }
              resolve()
            } else {
              this.cancelLoading(this.sceneModal)
              this.cancelLoading(this.sceneDelayModal)
              this.$Message.warning(data.message)
              reject()
            }
          })
          .catch((error) => {
            this.cancelLoading(this.sceneModal)
            this.cancelLoading(this.sceneDelayModal)
            this.$Message.error(error)
            reject()
          })
      })
    },
    // 查询当前比赛用户组信息
    getAccessGroupList() {
      let params = {
        pageIndex: 1,
        pageSize: 2147483647,
        testId: this.$route.query.id
      }
      getaccessgrouplist(params).then(({ code, data, message }) => {
        if (code == 1) {
          this.accessGroupList = data.items.map((item) => {
            return Object.assign(item, {
              groupId: item.id,
              userIds: item.userList.map((childItem) => {
                return childItem.userId
              })
            })
          })
        } else if (code == -2) {
          this.accessGroupList = []
        } else {
          this.$Message.warning(message)
        }
      })
    },
    timeChange(timeArr) {
      if (timeArr.length > 0) {
        this.formValidate.startTime = timeArr[0] ? timeArr[0] + ':00' : ''
        this.formValidate.endTime = timeArr[1] ? timeArr[1] + ':00' : ''
      }
    },
    showVisualization(val) {
      let oToken = localStorage.getItem('token')
      window.open(
        `${window.location.origin}/ctfPage/ctfCompetePlus.html?contestId=${this.$route.query.id}&token=${oToken}&projectId=${this.$route.query.prjid}&title=${this.pageTitle}`,
        '_black'
      )
      //线下测试
      // window.open(
      //    `http://localhost:8080/ctfCompetePlus.html?contestId=${this.$route.query.id}&token=${oToken}&projectId=${this.$route.query.prjid}`,
      //    '_black')
    },
    showVisualizationRank(val) {
      let oToken = localStorage.getItem('token')
      localStorage.setItem('oToken', oToken)
      localStorage.setItem('contestId', this.$route.query.id)
      window.open(
        `${window.location.origin}/ctfPage/teamRankPlus.html?title=${this.pageTitle}`,
        '_black'
      )
      // window.open(
      //    `http://localhost:9898/ctfPage/teamRankPlus.html`,
      //    '_black')
    },
    showVisualizationQuestion(val) {
      let oToken = localStorage.getItem('token')
      localStorage.setItem('oToken', oToken)
      localStorage.setItem('contestId', this.$route.query.id)
      window.open(
        `${window.location.origin}/ctfPage/answerSheetPlus.html?title=${this.pageTitle}`,
        '_black'
      )
    },
    changePreTab(name) {
      this.preDefault = name
      if (name == 'accessUser') {
      }
    },
    changeMidTab(name) {
      this.midDefault = name
      if (name == 'accessUser') {
      }
    },
    changeEndTab(name) {
      this.endDefault = name
      if (name == 'accessUser') {
      }
    },
    initPane() {
      this.preDefault = 'accessGroup'
      this.midDefault = 'targetTeamMid'
      this.endDefault = 'adwRankingStatic'
    },
    toPreCompeManage() {
      //演练前设置页面
      this.preDefault = 'accessGroup'
      this.midDefault = ''
      this.endDefault = ''
      this.currentIndex = 0
      setTimeout(() => {
        this.preCompeManagePanelShow = true
        this.compeingManagePanelShow = false
        this.compeedManagePanelShow = false
      })
    },
    toCompeingManage() {
      //演练中
      if (this.drillDetail.progress == 0 || this.drillDetail.progress == 1) {
        return
      }
      this.preDefault = ''
      this.midDefault = 'targetTeam'
      this.endDefault = ''
      this.currentIndex = 1
      setTimeout(() => {
        this.preCompeManagePanelShow = false
        this.compeingManagePanelShow = true
        this.compeedManagePanelShow = false
      })
    },
    toCompeedManage() {
      //演练后
      if (this.drillDetail.progress != 4) {
        return
      }
      this.preDefault = ''
      this.midDefault = ''
      this.endDefault = 'teamRankStatic'
      this.currentIndex = 2
      setTimeout(() => {
        this.preCompeManagePanelShow = false
        this.compeingManagePanelShow = false
        this.compeedManagePanelShow = true
      })
    },
    // 恢复暂停的比赛
    async restoreCompetition() {
      //加一个提示-bug15794
      this.tipModal.show = true
      this.tipModal.content = '正在恢复比赛...请稍后!!'
      await this.restoreCompetition_minixs(this.drillid) //方法在recoverTime混入中
      this.tipModal.show = false
    },
    // 暂停比赛
    pauseCompetition() {
      //加一个提示-bug15794
      this.tipModal.show = true
      this.tipModal.content = '正在暂停比赛...请稍后!!'
      this.changeCompetitionStatus(5, '暂停')
    },
    changeCompetitionStatus(status, op) {
      updateSceneProgress(this.drillid, status)
        .then((data) => {
          if (data.code == 1) {
            //this.$Message.info('修改演练场景成功');
            this.tipModal.show = false
            this.$Message.info(`${op}成功`)
            this.getDrillDetail()
            if (status == 2 && op == '开始') {
              //开始的时候调用
              this.setSceneCycle()
            }
          } else {
            this.$Message.error(data.message)
            this.tipModal.show = false
          }
        })
        .catch((error) => {
          this.tipModal.show = false
          this.$Message.error(error.message)
        })
    },
    validateStart() {
      this.canStartCompete(this.drillDetail.type).then((data) => {
        this.$Message.info('校验完成')
      })
    },
    getTaskList(status) {
      if (status == 2) {
        this.canStartCompete(this.drillDetail.type).then((data) => {
          if (!data) {
            this.$Message.warning('请检查团队成员配置及题目分配是否完成')
            return
          } else {
            if (new Date(this.drillDetail.endTime) - this.serveTime > 7 * 24 * 60 * 60 * 1000) {
              this.$Message.warning('无法开始比赛，比赛最长时间间隔为一周')
              return
            }
            this.opTaskListNew(status)
          }
        })
        this.tipModal.content = '正在开始比赛...请稍后!!'
      } else {
        this.tipModal.content = '正在停止比赛...请稍后!!'
        this.opTaskListNew(status)
      }
    },
    opTaskListNew(status) {
      this.tipModal.show = true
      let str
      if (status == 2) {
        //开始
        str = 'start'
      } else {
        str = 'stop'
      }
      let params = {
        sceneId: this.$route.query.id,
        taskMode: 'preset',
        op: str
      }
      this.changeCompetitionStatus(status, status == 2 ? '开始' : '结束')
    },
    opTaskList(status) {
      this.tipModal.show = true
      let opTask = []
      //flag持续任务
      let params1 = {
        testId: this.$route.query.id,
        page: 1,
        rows: 10000,
        taskType: 'loop_submit_flag',
        taskMode: 'preset'
      }
      let str
      if (status == 2) {
        //开始
        str = 'start'
      } else {
        str = 'stop'
      }
      let p1 = new Promise((resolve, reject) => {
        getTaskList(params1).then((data) => {
          if (data.code == 1) {
            let taskList = data.data.items
            taskList.forEach((task) => {
              if (status == 2) {
                if (task.status == 'initialized' || task.status == 'completed') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              } else if (status == 4) {
                if (task.status == 'running') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              }
            })
            resolve()
          }
        })
      })
      //Flag服务器配置
      let params2 = {
        testId: this.$route.query.id,
        page: 1,
        rows: 10000,
        taskType: 'once_server_flag',
        taskMode: 'preset'
      }
      let p2 = new Promise((resolve, reject) => {
        getTaskList(params2).then((data) => {
          if (data.code == 1) {
            let taskList = data.data.items
            taskList.forEach((task) => {
              if (status == 2) {
                //if(task.status == 'initialized'){
                opTask.push({
                  operation: str,
                  taskId: task.id
                })
                //}
              } else if (status == 4) {
                if (task.status == 'running') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              }
            })
            resolve()
          }
        })
      })
      //checker
      let params3 = {
        testId: this.$route.query.id,
        page: 1,
        rows: 10000,
        taskType: 'checker',
        taskMode: 'preset'
      }
      let p3 = new Promise((resolve, reject) => {
        getTaskList(params3).then((data) => {
          if (data.code == 1) {
            let taskList = data.data.items
            taskList.forEach((task) => {
              if (status == 2) {
                if (task.status == 'initialized' || task.status == 'completed') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              } else if (status == 4) {
                if (task.status == 'running') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              }
            })
            resolve()
          }
        })
      })
      //动态Flag配置
      let params4 = {
        testId: this.$route.query.id,
        page: 1,
        rows: 10000,
        taskType: 'loop_configure_flag',
        taskMode: 'preset'
      }
      let p4 = new Promise((resolve, reject) => {
        getTaskList(params4).then((data) => {
          if (data.code == 1) {
            let taskList = data.data.items
            taskList.forEach((task) => {
              if (status == 2) {
                if (task.status == 'initialized' || task.status == 'completed') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              } else if (status == 4) {
                if (task.status == 'running') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              }
            })
            resolve()
          }
        })
      })
      //数据通道
      let params5 = {
        testId: this.$route.query.id,
        page: 1,
        rows: 10000,
        taskType: 'tunnel',
        taskMode: 'preset'
      }
      let p5 = new Promise((resolve, reject) => {
        getTaskList(params5).then((data) => {
          if (data.code == 1) {
            let taskList = data.data.items
            taskList.forEach((task) => {
              if (status == 2) {
                if (task.status == 'initialized' || task.status == 'completed') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              } else if (status == 4) {
                if (task.status == 'running') {
                  opTask.push({
                    operation: str,
                    taskId: task.id
                  })
                }
              }
            })
            resolve()
          }
        })
      })
      Promise.all([p1, p2, p3, p4, p5]).then((data) => {
        console.log(opTask)
        this.activeTask(opTask).then((data) => {
          this.changeCompetitionStatus(status, status == 2 ? '开始' : '结束')
        })
      })
    },
    activeTask(tasks) {
      let $this = this
      return new Promise((resolve, reject) => {
        if (tasks.length == 0) {
          resolve()
        }
        batchActiveTask(tasks).then((response) => {
          let activeType
          if (response.code == 1) {
            if (response.data.length > 0 && response.data.some((task) => task.code == 0)) {
              response.data.forEach((task) => {
                if (task.code == 0) {
                  $this.$Message.warning(task.message)
                }
              })
            } else {
            }
            resolve()
          } else {
            $this.$Message.error(response.message)
          }
        })
      })
    },
    addBoardCast(val) {
      //添加公告
      let content = '"' + this.$route.query.name + '"竞赛 "' + val + '了"'
      let params = {
        broadid: '',
        content: content,
        drillitmeinstancetaskid: '',
        drillitmetaskname: '',
        sender: this.USER_ID,
        sendtime: '',
        teamid: '',
        title: content,
        type: 1
      }
      addBoardCast(params).then((data) => {
        if (data.code == 1) {
        }
      })
    },
    //添加场景周期
    setSceneCycle() {
      setSceneCycle(this.drillid).then((data) => {
        if (data.code == 1) {
          console.log(data.message)
        } else {
          this.$Message.warning(data.message)
        }
      })
    },
    //释放资源
    clearProject() {
      this.disabledDestroy = true
      clearProject(this.$route.query.prjid)
        .then((data) => {
          if (data.code == 1 || data.code == 3) {
            this.$Message.info('环境清空中...')
            clearInterval(this.timeoutP)
            this.timeoutP = setInterval((data) => {
              this.getProjectInfo()
            }, 3000)
          } else {
            this.$Message.warning(data.message)
          }
          this.disabledDestroy = false
        })
        .catch((error) => {
          this.disabledDestroy = false
        })
    },
    hideModal() {
      this.boardModal = false
    },
    destoryProject() {
      return (
        this.disabledDestroy ||
        !this.startContestStatus ||
        !this.stopContestStatus ||
        !(this.projectInfo.status == 3 || this.projectInfo.status == 14)
      )
    },
    returnPage() {
      this.$router.push(this.backObj)
    },
    gotoReportPage() {
      const { href } = this.$router.resolve({
        name: 'adcReport',
        query: {
          id: this.$route.query.id,
          type: 8,
          scoringType: this.scoringType
        }
      })
      window.open(href, '_blank')
    },
    resetEnviron() {
      this.tipModal.show = true
      this.tipModal.content = '正在重置环境...请稍后!!'
      batchOpVm(this.projectId, 'rebuild')
        .then((data) => {
          if (data.code == 1) {
            this.$Message.info('操作成功')
            this.batchOpVmLog()
          } else {
            this.$Message.error(data.message)
          }
          this.tipModal.show = false
        })
        .catch((error) => {
          this.$Message.error('环境重置失败')
          this.tipModal.show = false
        })
    },
    batchOpVmLog(isFirst) {
      batchOpVmLog(this.queryOpLogInfo)
        .then((data) => {
          if (data.code == 1) {
            if (data.data.items.length > 0) {
              //重置过
              let id = data.data.items[0].id
              this.batchOpVmLogDetail(id, isFirst)
            } else {
              //未重置
              this.resetStatus = 0
            }
          } else {
            this.$Message.error(data.messsage)
          }
        })
        .catch((error) => {
          this.$Message.error('查询重置详情失败')
        })
    },
    batchOpVmLogDetail(id, isFirst) {
      batchOpVmLogOnce(id)
        .then((data) => {
          if (data.code == 1) {
            this.resetInfo = data.data
            this.resetInfo.finished = this.resetInfo.finished || 0
            this.resetProgress = parseInt((this.resetInfo.finished / this.resetInfo.total) * 100)
            console.log(
              (this.resetInfo.finished / this.resetInfo.total).toFixed(2),
              this.resetProgress
            )
            if (this.resetInfo.finished == this.resetInfo.total) {
              this.resetStatus = 2 // 重置完成
              if (this.resetInfo.msgs.filter((item) => item.errMsg).length > 0) {
                this.resetFail = true
                if (!isFirst) {
                  this.$Message.error('重置失败')
                }
              } else {
                this.resetFail = false
                if (!isFirst) {
                  this.$Message.info('重置成功')
                }
              }
            } else if (this.resetInfo.finished < this.resetInfo.total) {
              this.resetStatus = 1 //重置中
            }
            if (this.resetStatus != 2) {
              setTimeout(() => {
                this.batchOpVmLogDetail(id)
              }, 2000)
            }
          } else {
            this.$Message.error(data.messsage)
          }
        })
        .catch((error) => {
          this.$Message.error('查询重置详情失败')
        })
    },
    getResetDetail() {
      this.resetDetailModal.show = true
    },
    rebuildAllFailVm() {
      this.tipModal.show = true
      this.tipModal.content = '正在重置环境...请稍后!!'
      let proArr = this.resetInfo.msgs
        .filter((item) => item.errMsg)
        .map(async (vm) => {
          await this.rebuildVm(vm.id)
        })
      Promise.all(proArr)
        .then((data) => {
          this.tipModal.show = false
          this.$Message.info('重置完成')
        })
        .catch((error) => {
          this.$Message.info('重置失败')
        })
    },
    rebuildVm(id) {
      return new Promise((resolve, reject) => {
        rebuildVm(id)
          .then((data) => {
            if (data.code == 1) {
              resolve(data)
            } else {
              reject()
            }
          })
          .catch((error) => {
            reject()
          })
      })
    },
    showDelayModal() {
      this.sceneDelayModal.show = true
      this.getDrillDetail('', '', 'setEndDate').then(() => {
        this.formValidate = Object.assign(this.formValidate, this.drillDetail)
        this.formValidate.endDate = this.formValidate.endTime
      })
    },
    changeEndDate(time) {
      this.formValidate.endDate = time ? time + ':00' : ''
    },
    addSceneCycle() {
      let sceneId = this.$route.query.id
      addSceneCycle(sceneId)
        .then((data) => {
          if (data.code == 1) {
            //this.$Message.info('创建场景周期成功!');
          } else {
            this.$Message.error(data.message)
          }
        })
        .catch((error) => {
          this.$Message.error('创建场景周期失败!')
        })
    },
    clearSceneNoticeAndChat() {
      const msg = this.$Message.loading({
        content: '正在清空...',
        duration: 0,
        closable: true
      })
      let sceneId = this.$route.query.id
      clearSceneNoticeAndChat(sceneId)
        .then((data) => {
          setTimeout(msg, 1000)
          setTimeout(() => {
            if (data.code == 1) {
              this.$Message.info('清空成功')
              this.$refs['chatRoom'].clearChatMsg()
            } else {
              this.$Message.info('清空失败')
            }
          }, 1100)
        })
        .catch((error) => {
          setTimeout(msg, 1000)
          setTimeout(() => {
            this.$Message.info('清空失败')
          }, 1100)
        })
    }
  }
}
</script>
<style scoped src="./detail.css"></style>
